package edu.zjut.hjg.saas.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.zjut.hjg.saas.biz.dao.ResourceDao;
import edu.zjut.hjg.saas.biz.model.City;
import edu.zjut.hjg.saas.biz.model.Province;
import edu.zjut.hjg.saas.biz.model.Resource;
import edu.zjut.hjg.saas.biz.service.LocationService;

public class LocationServiceImpl implements LocationService {
    private static final Log    log          = LogFactory.getLog(LocationServiceImpl.class);
    private static final String KEY_PROVINCE = "RESOURCE_KEY_PROVINCE";
    private static final String KEY_CITY     = "RESOURCE_KEY_CITY";

    private ResourceDao         resourceDao;

    public void setResourceDao(ResourceDao resourceDao) {
        this.resourceDao = resourceDao;
    }

    @Override
    public City findCityByCityCode(String cityCode) {
        Resource cityResource = resourceDao.findByResourceKeyAndRealValue(KEY_CITY, cityCode);
        if (cityResource == null) {
            log.error("no city found: cityCode=" + cityCode);
            throw new RuntimeException("no city found: cityCode=" + cityCode);
        }
        Resource proviceResource = resourceDao.load(cityResource.getParentId());
        Province provnice = resourceToProvice(proviceResource);
        City city = resourceToCity(cityResource);
        city.setProvince(provnice);
        return city;
    }

    @Override
    public List<Province> listAllProvinces() {
        List<Resource> resources = resourceDao.listByResourceKey(KEY_PROVINCE);
        List<Province> provinces = new ArrayList<Province>(resources.size());
        for (Resource resource : resources) {
            provinces.add(resourceToProvice(resource));
        }
        return provinces;
    }

    @Override
    public List<City> listCitesByProvinceCode(String proviceCode) {
        List<Resource> resources = resourceDao.listChildrenByParentResourceKeyAndRealValue(
                KEY_PROVINCE, proviceCode);
        List<City> cities = new ArrayList<City>(resources.size());
        for (Resource resource : resources) {
            cities.add(resourceToCity(resource));
        }
        return cities;
    }

    private City resourceToCity(Resource resource) {
        City city = new City();
        city.setCode(resource.getRealValue());
        city.setName(resource.getDisplayValue());
        return city;
    }

    private Province resourceToProvice(Resource resource) {
        Province provnice = new Province();
        provnice.setCode(resource.getRealValue());
        provnice.setName(resource.getDisplayValue());
        return provnice;
    }
}
